package com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.my_order_list.chlid

import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.appcompat.widget.Toolbar
import com.alibaba.fastjson.JSON
import com.example.library_common.album.view.grid_view.XGridLayout
import com.example.library_common.album.view.grid_view.adapter.CommAdapter
import com.example.library_common.album.view.grid_view.adapter.XQuickViewHolder
import com.example.library_common.base.BaseFragmentEx
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.even.MessageWrap
import com.example.library_common.utils.even.TO_REFRESH_LIST
import com.example.library_common.utils.upload_file.UploadFileWorker
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.bean.SstShopOrderChild
import com.example.shushiyunsst.fragment.main.home.child.new_sale.chlid.my_order_list.chlid.bean.OrderInfoBean
import com.example.wallet.db.UserInfoManager
import com.google.android.material.checkbox.MaterialCheckBox
import me.zhanghai.android.materialratingbar.MaterialRatingBar
import org.greenrobot.eventbus.EventBus
import java.lang.StringBuilder

class MyOrderCommentFragment : BaseFragmentEx() {


    companion object {
        fun newInstance(orderId: String): MyOrderCommentFragment {
            val args = Bundle()
            args.putString("orderId", orderId)
            val fragment = MyOrderCommentFragment()
            fragment.arguments = args
            return fragment
        }
    }


    private lateinit var goodsDegree: RadioGroup

    private lateinit var goodsComment: EditText

    private lateinit var goodsMatch: MaterialRatingBar

    private lateinit var deliveryService: MaterialRatingBar

    private lateinit var service: MaterialRatingBar

    private lateinit var hideComment: MaterialCheckBox

    private lateinit var submitBtn: TextView

    private lateinit var mXGridLayout: XGridLayout

    private var orderId: String? = ""

    private var mAddImg = DrawbackAddImgFragment.newInstance()

    private var mUploadFileWorker: UploadFileWorker? = null

    private var orderInfo: OrderInfoBean? = null

    private var mAdapter: CommAdapter<SstShopOrderChild>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        orderId = arguments?.getString("orderId", "")
    }


    override fun getLayoutId(): Any {
        return R.layout.my_order_comment_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val mToolbar:Toolbar =view.findViewById(R.id.mToolbar)
        mToolbar.title="评价订单"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }

        mXGridLayout = view.findViewById(R.id.mXGridLayout)

        goodsDegree = view.findViewById(R.id.goodsDegree)
        goodsComment = view.findViewById(R.id.goodsComment)
        goodsMatch = view.findViewById(R.id.goods_match)
        deliveryService = view.findViewById(R.id.delivery_service)
        service = view.findViewById(R.id.service)
        hideComment = view.findViewById(R.id.hide_comment)
        submitBtn = view.findViewById(R.id.submit_btn)

        submitBtn.setOnClickListener {
            send()
        }

        mAdapter = object : CommAdapter<SstShopOrderChild>
            (_mActivity, R.layout.my_order_comment_item_fragment) {
            override fun convert(
                holder: XQuickViewHolder?,
                item: SstShopOrderChild?,
                position: Int
            ) {
                holder?.setText(R.id.name, item?.goodsName)
                    ?.displayImage(R.id.icon, item?.goodsLogo)
            }

        }
        mXGridLayout.setAdapter(mAdapter, lifecycle)

        loadRootFragment(R.id.imgList, mAddImg)
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo



        val map = mapOf(
            "orderId" to orderId,
            "uid" to userInfo?.uid,

        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryOrderInfoById)
            .success {
                parseOrderInfo(it)
            }.failure {
                Toast.makeText(_mActivity, "获取订单信息失败", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    private fun parseOrderInfo(it: String?) {
        val obj = JSON.parseObject(it)
        val order = obj["order"].toString()
        orderInfo = JSON.parseObject(order, OrderInfoBean::class.java)

        if (orderInfo?.isChild == 0) {
            val child = SstShopOrderChild()
            child.createTime = orderInfo?.createTime
            child.goodsColor = orderInfo?.goodsColor
            child.goodsId = orderInfo?.goodsId ?: 0
            child.goodsLogo = orderInfo?.goodsLogo
            child.goodsName = orderInfo?.goodsName
            child.goodsNums = orderInfo?.goodsNums ?: 0
            child.goodsPrice = orderInfo?.goodsPrice ?: 0.0
            child.orderId = orderInfo?.orderId ?: 0
            child.goodsSize = orderInfo?.goodsSize
            child.orderStatus = orderInfo?.orderStatus ?: 0
            orderInfo?.childOrds?.add(child)
        }
        mAdapter?.clear()
        mAdapter?.addAll(orderInfo?.childOrds)
    }

    private fun send() {
        val selector = mAddImg.getSelector()

        if (selector.isEmpty()) {
            toSendData("")
            return
        }

        val mutableListOf = mutableListOf<String>()

        for (e in selector) {
            mutableListOf.add(e.path)
        }

        mUploadFileWorker = UploadFileWorker()
        mUploadFileWorker?.setListener(object : UploadFileWorker.UpLoadOverListener {
            override fun onUpLoadOver(res: List<String>) {
                mUploadFileWorker = null
                var str = StringBuilder()
                for (w in res) {
                    str.append(w)
                        .append(",")
                }

                if (str.isNotEmpty()) {
                    str = str.deleteCharAt(str.lastIndexOf(","))
                }

                toSendData(str.toString())
            }
        })?.doWork(mutableListOf)
    }

    private fun toSendData(assessPics: String) {

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val assessLevel = when(goodsDegree.checkedRadioButtonId){
            R.id.good->1
            R.id.middle->2
            R.id.worst->3
            else ->1
        }

        val isAnonymous =  if(hideComment.isChecked) 1 else 0
        val map = mapOf(
            "orderId" to orderId,
            "uid" to userInfo?.uid,
            "assessLevel" to assessLevel,
            "assessPics" to assessPics,
            "descStar" to goodsMatch.rating,
            "isAnonymous" to isAnonymous,
            "orderId" to orderInfo?.orderId,
            "speedStar" to deliveryService.rating,
            "serviceStar" to service.rating
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.saveOrderAssess)
            .success {
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_SHORT).show()
                EventBus.getDefault().post(MessageWrap.getInstance(TO_REFRESH_LIST))
                onBackPressedSupport()
            }.failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }
}